<template>
  <el-dialog
    ref="k_dia"
    :title="title"
    :visible.sync="open"
    width="90%"
    :z-index="1000"
    :close-on-click-modal="false"
    class="dia-style k-dia"
    @close="handleCancel"
  >
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      @submit.native.prevent
    >
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="ruleForm.templateName" maxlength="50" />
      </el-form-item>
      <el-form-item label="模板类型" prop="templateType">
        <el-select v-model="ruleForm.templateType" filterable placeholder="请选择" @focus="setMinWidth">
          <el-option
            v-for="item in templateTypeOptions"
            :key="item.itemVale"
            :title="item.itemLabel"
            :style="{'max-width': maxWidth + 2 + 'px'}"
            :label="item.itemLabel"
            :value="item.itemVale"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <!-- 富文本编辑器  -->
        <div class="hk-flex">
          <div style="width: 70%">
            <draggable
              v-model="arr2"
              style="width:100%;height:100%"
              :group="groupB"
              animation="300"
              drag-class="dragClass"
              ghost-class="ghostClass"
              chosen-class="chosenClass"
              @start="onStart"
            >
              <Editor ref="myQuillEditor" :value="content" @on-change="changeEdit" />
            <!--   <vue-tinymce
                ref="tinymceRef"
                v-model="content"
                :setting="setting"
              /> -->
            </draggable>

          </div>
          <div class="draggable-box">
            <el-input v-model="keyword" placeholder="请输入内容" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
            </el-input>
            <div v-for="(item, index) in draggableArr" :key="item.name + index" class="draggable-lists">
              <div class="collapse-title" @click="item.isShow = !item.isShow">
                <i :class="item.isShow ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" />{{ item.name }}
              </div>
              <draggable
                v-if="item.isShow"
                v-model="draggableArr"
                :group="groupA"
                animation="300"
                drag-class="dragClass"
                ghost-class="ghostClass"
                chosen-class="chosenClass"
                @end="onEnd($event, item)"
              >
                <transition-group>
                  <div v-for="(i, indx) in item.arr" :key="i + indx" class="draggable-list">
                    <span :title="i">{{ i }}</span><i class="el-icon-circle-plus" @click.stop="insert(i)" />
                  </div>
                </transition-group>
              </draggable>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="footer-btn">
      <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Editor from '@/components/Editor'
import Vue from 'vue'
// 导入draggable组件
import draggable from 'vuedraggable'
import { addTemplate, getTemplate, updateTemplate, getPlaceholder } from '@/api/riskProduct/templateManage'
export default Vue.extend({
  // components: { Editor, Toolbar, draggable },
  components: { Editor, draggable },
  props: {
    title: {
      type: String,
      default() {
        return '新增'
      }
    },
    templateTypeOptions: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      open: false,
      //  id
      currentId: null,
      editor: null,
      content: '',
      toolbarConfig: {},
      // 表单配置
      ruleForm: {
        templateName: null,
        templateType: null
      },
      rules: {
        templateName: [
          {
            required: true,
            message: '请输入模块名称',
            trigger: 'blur'
          }
        ]
      },
      //  拖拽数据配置
      draggableArr: [],
      defaultArr: [],
      arr2: [],
      groupA: {
        name: 'site',
        pull: false, // 可以拖入
        put: false // 可以拖出
      },
      groupB: {
        name: 'site2',
        pull: true,
        put: true
      },
      keyword: '',
      activeIndex: 0,
      // 是否可编辑
      isPreset: null,
      maxWidth: null
    }
  },
  mounted() {},
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    // 设置下拉框的宽度
    setMinWidth(val) {
      //  webkit内核
      if (val.srcElement) {
        this.maxWidth = val.srcElement.clientWidth
      }
      //  火狐内核
      if (val.target) {
        this.maxWidth = val.target.clientWidth
      }
    },
    //  显示弹窗
    show(type, id, isPreset) {
      this.open = true
      this.isPreset = isPreset
      this.keyword = ''
      this.getPlaceholderData()
      if (id) {
        this.currentId = id
        this.getCurrentData(id)
      }
    },
    //  获取富文本编辑器的内容
    getCurrentData(id) {
      getTemplate({ id: id }).then((res) => {
        this.ruleForm = {
          templateName: res.templateName,
          templateType: res.templateType
        }
        this.content = res.content
        // if (res.content.includes('<html')) {
        //   const bodyContent = res.content.split('<body>')[1].split('</body')[0].replaceAll('div', 'p')
        //   this.content = bodyContent
        // } else {
        //   this.content = res.content
        // }
      })
    },
    //  富文本编辑器创建
    /*  onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      //  判断是否可编辑
      if (this.isPreset == '1') {
        this.editor.disable()
      }
    }, */
    // 调用该方法插入内容
    insert(data) {
      // 获取编辑器对象
      const quill = this.$refs.myQuillEditor.Quill
      // 获取编辑器光标位置
      let index = quill.selection.savedRange.index

      // 插入文本至光标位置，
      quill.insertText(index, data)

      // 重新计算index
      index += data.length

      // 移动光标至文本后面
      quill.setSelection(index)
    },
    //  富文本变化
    changeEdit(html) {
      this.content = html.html
    },
    //  点击右侧折叠标签
    handleToggle(index) {
      // this.activeIndex = index
      this.isShow = true
    },
    //  拖拽事件
    onStart(e) {
    },
    onEnd(e, item) {
      this.insert(item.arr[e.oldDraggableIndex])
      // const showText = `{{${item.arr[e.oldDraggableIndex].name}}}`
      // this.content = this.content.replace(e.item.innerText, showText)
    },
    //  获取右侧分类占位符
    getPlaceholderData() {
      getPlaceholder().then((res) => {
        this.draggableArr = []
        const keys = Object.keys(res)
        keys.forEach((i, index) => {
          this.draggableArr.push({
            name: i,
            arr: res[i],
            isShow: false
          })
        })
        this.defaultArr = JSON.parse(JSON.stringify(this.draggableArr))
      })
    },
    //  右侧占位符查询
    handleSearch() {
      this.defaultArr.forEach((item, index) => {
        this.draggableArr[index].isShow = true
        this.draggableArr[index].arr = item.arr.filter((i) => {
          return i.includes(this.keyword)
        })
      })
    },
    //  关闭弹窗
    handleCancel() {
      this.content = ''
      this.open = false
      this.$refs['ruleForm'].resetFields()
    },
    //  保存按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let html = null
          if (!this.content.includes('link')) {
            html = `<link  rel="stylesheet" href="${window.location.origin}/zjg/static/quill.core.css"/><link  rel="stylesheet" href="${window.location.origin}/zjg/static/quill.snow.css"/><link  rel="stylesheet" href="${window.location.origin}/zjg/static/quill.bubble.css"><div class='ql-editor'>`
            html += this.content
            html += '</div>'
          } else {
            html = this.content
          }
          if (!this.currentId) {
            addTemplate({ ...this.ruleForm, content: html }).then((res) => {
              this.$message.success('保存成功')
              this.$emit('handleSubmit')
              this.handleCancel()
            })
          } else {
            updateTemplate({ ...this.ruleForm, content: html, id: this.currentId }).then((res) => {
              this.$message.success('保存成功')
              this.$emit('handleSubmit')
              this.handleCancel()
            })
          }
        } else {
          return false
        }
      })
    }
  }
})
</script>
<style lang="scss" scoped>
::v-deep .tox-tinymce-aux{
  z-index:5000 !important;
}
::v-deep .tox-statusbar{
  display:none
}
::v-deep .el-select--medium {
  width: 100% !important;
}
.hk-flex {
  align-items: stretch;
}
.el-form {
  padding: 20px 20px 0 !important;
}
.draggable-box {
  height:500px;
  overflow: auto;
  width: 30%;
  padding: 20px 20px;
  background: #f8f9fc;
  .draggable-lists {
    padding: 5px 0;
    >div:nth-child(2){
      >span{
        width:100%;
        flex-wrap: wrap;
        display:flex;
        justify-content: space-between;
      }
    }
    .draggable-list {
      width:49%;
      padding: 0px 10px;
      background: #cbe4fd;
      border: 1px solid #1d74e2;
      border-radius: 4px;
      margin-bottom: 5px;
      display: flex;
      align-items: center;
      span {
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        flex: 1;
      }
      .el-icon-circle-plus {
        color: #1d74e2;
        cursor: pointer;
      }
    }
  }
}
.footer-btn {
  text-align: right;
}
/*定义要拖拽元素的样式*/
.ghostClass {
  background-color: #cbe4fd !important;
}
.chosenClass {
  background-color: #cbe4fd !important;
  opacity: 0.4 !important;
}
.dragClass {
  background-color: #cbe4fd !important;
  opacity: 0.8 !important;
  box-shadow: none !important;
  outline: none !important;
  background-image: none !important;
}
</style>
